﻿/*
 * Created by SharpDevelop.
 * User: phtrung
 * Date: 4/2/2010
 * Time: 9:25 AM
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */

using System;
using System.Collections.Generic;
using System.Collections;
using System.Drawing;
using System.Windows.Forms;
using System.IO;
using popLib;

namespace ApacheConfig
{
	/// <summary>
	/// Description of MainForm.
	/// </summary>
	public partial class MainForm : Form
	{
		string config_org = "";
		List<VirtualHost> host = new List<VirtualHost>();
		int currentindex = -1;		
		
		public MainForm(string[] args)
		{
			//
			// The InitializeComponent() call is required for Windows Forms designer support.
			//
			InitializeComponent();
			
			//FormLib.alert( Environment.GetFolderPath(Environment.SpecialFolder.System) );			
			
			FormLib.dragAndDrop( this, doDrag );
			FormLib.dragAndDrop( lbx_virtualhost, doDrag );
			FormLib.dragAndDrop( lbl_configfile, doDrag );
			
			if( args.Length > 0 && File.Exists(args[0]) ){
				openFile( args[0] );
			}
			
		}
		
		void doDrag(Control sender, string[] files){
			openFile( files[0] );
		}
		
		void Btn_loadConfigClick(object sender, EventArgs e)
		{
			ReturnSet rs = FormLib.openFile("Apache config file(*.conf)|*.conf");
			if( rs.Success ){
				openFile( rs.Result.ToString() );
			}
		}
		
		void openFile( string file ){
			if( !File.Exists(file) ) return;
			lbl_configfile.Text = file;
			config_org = FileLib.readFile(lbl_configfile.Text);
	
			//get port
			nud_port.Value = NumberLib.getInt( StringLib.subStringBetween( config_org, "#Listen [::]:80", "#", 0 ) );
			
			
			//set server name
			string servername = StringLib.subStringBetween( config_org, @"#
ServerName", "#", 0 );
			txt_server.Text = servername.Split(':')[0].Trim();
			

			//get namevirtualhost
			txt_namevirtualhost.Text = StringLib.subStringBetween(config_org, "NameVirtualHost", "\r\n", 0).Trim();				
			
			//get all virtual host
			host.Clear();
			ArrayList hostStrArr = StringLib.getListGroupString( config_org.Substring(config_org.LastIndexOf("</IfModule>")), "<VirtualHost", "</VirtualHost>" );
			foreach( string hostStr in hostStrArr ){
				string[] lines = StringLib.splitByAny( hostStr, "\r\n".Split(',') );
				VirtualHost virtualhost  = new VirtualHost();
				virtualhost.ServerName   = lines[1].ToLower().Replace("servername","").Trim();
				virtualhost.DocumentRoot = lines[2].ToLower().Replace("documentroot","").Trim();					
				host.Add( virtualhost );
			}				
			updateList();
		}
		
		string getStringBetweenPath( string[] begins, string end, string src ){
			string markStr="";
			foreach( string begin in begins ){
				if( src.Contains( begin ) ){
					markStr = begin;
				}
			}
			if( markStr == "" ) return null;
			return StringLib.subStringBetween( src, markStr, end, 0 );
		}
		
		
		void Lbx_virtualhostSelectedIndexChanged(object sender, EventArgs e)
		{
			if( lbx_virtualhost.SelectedIndex == -1 ) return;
			txt_servername.Text = host[lbx_virtualhost.SelectedIndex].ServerName;
			txt_docRoot.Text    = host[lbx_virtualhost.SelectedIndex].DocumentRoot;
			currentindex = lbx_virtualhost.SelectedIndex;
		}
		
		//new item
		void Button1Click(object sender, EventArgs e)
		{
			txt_servername.Text = txt_docRoot.Text = "";
			currentindex = -1;
			lbx_virtualhost.SelectedIndex = -1;
		}
		
		//save item
		void Btn_savehostClick(object sender, EventArgs e)
		{
			if( currentindex >= 0 ){
				host[currentindex].DocumentRoot = txt_docRoot.Text;
				host[currentindex].ServerName   = txt_servername.Text;
			}else{
				VirtualHost virtualhost = new VirtualHost();
				virtualhost.DocumentRoot = txt_docRoot.Text;
				virtualhost.ServerName   = txt_servername.Text;
				host.Add( virtualhost );				
			}
			
			updateList();
		}
		
		void updateList(){
			lbx_virtualhost.Items.Clear();
			foreach( VirtualHost virtualhost in host )
				lbx_virtualhost.Items.Add( virtualhost.ServerName );
		}
		
		void Btn_docrootClick(object sender, EventArgs e)
		{
			ReturnSet rs = FormLib.folderBrowser( System.Environment.SpecialFolder.Desktop, false);
			if( rs.Success ){
				txt_docRoot.Text = rs.Result.ToString();
			}
		}
		
		void Btn_updateClick(object sender, EventArgs e)
		{
			string result = config_org;
			
			result = result.Replace(StringLib.subStringBetween(result, "#Listen [::]:80", "#", 0), 
			                        "\r\nListen "+nud_port.Value+"\r\n" );
			
			
			result = result.Replace(StringLib.subStringBetween(result, @"# If your host doesn't have a registered DNS name, enter its IP address here.
#", @"#
# DocumentRoot: The directory out of which you will serve your", 0), 
			                        "\r\nServerName "+txt_server.Text+":"+nud_port.Value+"\r\n" );
			
			result = result.Substring( 0, result.LastIndexOf("</IfModule>") + "</IfModule>".Length ) + "\r\n\r\n";
			
			result += "\r\nNameVirtualHost "+txt_namevirtualhost.Text+"\r\n\r\n";
			
			string commentedHost = @"#<VirtualHost {0}>
#  ServerName {1}
#  DocumentRoot ""{2}""
#</VirtualHost>

#<Directory ""{2}"">
#  Options All
#  Allow from All
#  Order Allow,Deny
#  AllowOverride All
#</Directory>

";
			
			string availableHost = commentedHost.Replace("#","");
			
			string winHost = @"# Copyright (c) 1993-1999 Microsoft Corp.
#
# This is a sample HOSTS file used by Microsoft TCP/IP for Windows.
#
# This file contains the mappings of IP addresses to host names. Each
# entry should be kept on an individual line. The IP address should
# be placed in the first column followed by the corresponding host name.
# The IP address and the host name should be separated by at least one
# space.
#
# Additionally, comments (such as these) may be inserted on individual
# lines or following the machine name denoted by a '#' symbol.
#
# For example:
#
#      102.54.94.97     rhino.acme.com          # source server
#       38.25.63.10     x.acme.com              # x client host

127.0.0.1  localhost
";
			
			foreach( VirtualHost virtualhost in host ){
				result += string.Format( (virtualhost.ServerName.StartsWith("#") ? commentedHost : availableHost), 
				                        txt_namevirtualhost.Text, 
				                        virtualhost.ServerName.Replace("#",""), 
				                        virtualhost.DocumentRoot);
				
				winHost += ( virtualhost.ServerName.StartsWith("#") ? "#" : "" ) + "127.0.0.1  "+virtualhost.ServerName.Replace("#","")+"\r\n" ;
			}
			
			string conf_file = lbl_configfile.Text;			
			string bak_file = conf_file + ".bak";
			File.Copy( conf_file , bak_file, true );
			
			FileLib.writeFile( conf_file, result );
						
			string hosts_file = Environment.GetFolderPath(Environment.SpecialFolder.System) + @"\drivers\etc\hosts";
			FileLib.writeFile( hosts_file + ".txt", winHost );
			File.Delete( hosts_file );
			File.Move( hosts_file + ".txt", hosts_file );
			
			FormLib.alert("Update File completed");
		}
		
		void Lbx_virtualhostKeyUp(object sender, KeyEventArgs e)
		{
			if( e.KeyCode == Keys.Delete && lbx_virtualhost.SelectedIndex >= 0 ){
				if( host.Count <= lbx_virtualhost.SelectedIndex) return;				
				host.RemoveAt( lbx_virtualhost.SelectedIndex );
				updateList();
			}
		}
	}
	
	public class VirtualHost{
		private string _ServerName;
		public string ServerName{ 
			get{return _ServerName;} 
			set{
				_ServerName = (value.Contains("#") ? "#" : "") + fixString(value);
			} }

		private string _DocumentRoot;
		public string DocumentRoot{ 
			get{return _DocumentRoot;} 
			set{_DocumentRoot = fixString(value);} }
		
		private string fixString(string value){
			if( value.StartsWith("#") )
				value = value.Substring(1);
			return value.Replace("\"","").Trim();
		}
	}
}
